﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace NotifyApplication.Controllers
{
    public class Constant { 
        //商户私钥
        public static string PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCc540quYC9xzCMZeFOe8UmE3W5LWrqFd/2DDSHQASxq8vmOiwFRSG2hsVXtjfmNLQNhtpTR0SGDUjkCsx+SJH0JDnOfQ2xXHasO65Rnv2wrHs64P6U0aUrMWjgapjkmLwzRV12AKNAX77MGIocpcB0KZhk+0AVc6oQCBybV65JTGu+pAyFLMJRtIP5kH3VMuXmig6VeiZAsjEewD/emxgK3cXejMQvqlNYFnCLsZ7ovAhr+bhz6SHkOws3p80O6zfQbKfLzdSVaZK8FnwNPznUxAK77bRZN0zF3V9mL9+zrarvFPD5VkcVHNLj0DRzLmr2c5TbiCigs4+I+NMfhpoLAgMBAAECggEAbM8GzoImDXV87WAZhtu+NFF6ahhc9EiHL5H3O3PhzXRdyiK9NEpkvrdnUxRCX5pc4qSJ8waRNoUv7zSt60VYMf6NN+zw+fYtNfONR30CYOq76nDtGzbnW7TADiDeNmjU2plX3uVCUPoUzmSWIpevht7xl9XE8xtq7AM0E2YSrzEADcxtqQslM0uVOf+ki1eu0/OwCz13FzPlPtnDwt2Lw9xxCxWqTgpN4oD5m6EWTqbognUIJ0EFD0dHXjrYnHXc+/Za5e+CDXYApHuhR9bifa1e4HMN084oLY+rkSXUV3+Te0APPCfbeEeqvubziDmKxxKaWUq1wPbYi4c06ZQdgQKBgQDhF7zDWgiJFTgrLGmExJRKiR/3QZN4sugYE1itdRDJmiPV4xhWPXSsND3WtqR5+0otb/hbzRa3cyl/RXV/1ZmBbE46fX2DKnmLQ1gP74iOuqWpfxjh/qpk+3kEY9aP57le/O0QEEPsJmqCsGM7XnzfNsxGAFYaDHooRbcGtv++AwKBgQCycuvRUQjV4dxTuRJuwFbmdq4odSBMu7yCS4i5I9I73d3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AQAB";
        //招行公钥
        public static string CMB_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjutZyxP2L9eYM6DhZ11jk5lZieyyA6Wsr4baAU7PT+E0fv3KlERoh0edHLsLVff2I4AzuEqSoKDywKIBw1aSkIXGAaESj/FzA/V1jtmorq1RpPFmaqAOGDocMiaqukBBemwFnsYrTegsZUf88fU7KujwEMffLhhpwnM/Vf0NJ2s3ZwEZCgPWDa5cm1YpMLgopzc5HozENI5K9VFL92ThjHiTiutE28Bpi2xgSt6Cx+S8Nxqhy6/r/YVxvfgP66YCccnWOObN3fWo5TXepP6uBReTwjqNajlcSC5JqINqUUEAqief87y3NAFKRbE7Bu312y6zqcJgC/TIrWLXXB1/XQIDAQAB";
    }

    public class NotifyController : Controller
    {
        //
        // GET: /Notify/

        public ActionResult Index()
        {
            var sr = new StreamReader(Request.InputStream);
            string requestBodyString = sr.ReadToEnd();
            System.Diagnostics.Debug.WriteLine("参数1:" + requestBodyString);
            requestBodyString = Server.UrlDecode(requestBodyString);
            System.Diagnostics.Debug.WriteLine("参数2:" + requestBodyString);
            Dictionary<string, string> respData = new Dictionary<string, string>();
            //设置响应数据
            respData.Add("version", "0.0.1");//版本号，固定为0.0.1(必传)
            respData.Add("encoding", "UTF-8");//编码方式，固定为UTF-8(必传)
            respData.Add("signMethod", "01");//签名方法，固定为01,表示签名方法为RSA2(必传)
            respData.Add("respCode", "SUCCESS");//响应错误码，为SUCCESS(必传)
            try {
                //非空校验
                if (requestBodyString == null || "".Equals(requestBodyString.Trim())) {
                    System.Diagnostics.Debug.WriteLine("参数为空");
                    respData.Add("returnCode", "FAIL");
                    return Json(respData);
                }
                
                Dictionary<string, string> requestBodyMap = SignatureUtil.str2Map(requestBodyString);
                Dictionary<string, string> resultMap = new Dictionary<string,string>();
                foreach (KeyValuePair<string, string> kvp in requestBodyMap)
                {
                    string key = kvp.Key;
                    string value = kvp.Value;
                    System.Diagnostics.Debug.WriteLine("key:" + key);
                    System.Diagnostics.Debug.WriteLine("value:" + value);
                    resultMap.Add(key, value);
                }
                if (resultMap.Count == 0) {
                    respData.Add("returnCode", "FAIL");
                    return Json(respData);
                }
                string sign = resultMap["sign"];
                if (sign == null)
                {
                    respData.Add("returnCode", "FAIL");
                    return Json(respData);
                }
                resultMap.Remove("sign");
                //对待加签内容进行排序拼接
                string contentStr = SignatureUtil.GetSignContent(resultMap);
                System.Diagnostics.Debug.WriteLine("contentStr：" + contentStr);
                System.Diagnostics.Debug.WriteLine("sign：" + sign);
                //验证签名-使用招行公钥进行验签
                bool flag = SignatureUtil.GetRsaCheck(contentStr, sign, Constant.CMB_PUBLIC_KEY, "UTF-8");
                if (!flag) {
                    //验签失败
                    System.Diagnostics.Debug.WriteLine("验签失败");
                    respData.Add("returnCode", "FAIL");
                    return Json(respData);;
                }
                System.Diagnostics.Debug.WriteLine("验签成功");
                //......（处理自身业务逻辑）
                //......
                //......
                respData.Add("returnCode", "SUCCESS");//业务错误码，成功为SUCCESS，失败为FAIL
                /*如果处理自身业务逻辑发生错误，返回
                respData.put("respCode","FAIL");
                respData.put("respMsg","error_msg");
                */
                //对待加签内容进行排序拼接
                string signContent = SignatureUtil.GetSignContent(respData);
                //加签-使用商户私钥加签
                string signR = SignatureUtil.GetRsaSign(signContent, Constant.PRIVATE_KEY, "UTF-8");
                System.Diagnostics.Debug.WriteLine("signR:" + signR);
                respData.Add("sign", signR);
                System.Diagnostics.Debug.WriteLine("加签成功");
                return Json(respData);
            } catch (Exception e) {

                System.Diagnostics.Debug.WriteLine(e.Message);
                respData.Add("returnCode", "FAIL");
                return Json(respData);
            }
        }
    }
}
